package com.rainbowsea.yupicturebackend.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.qcloud.cos.utils.IOUtils;
import com.rainbowsea.yupicturebackend.config.CosClientConfig;
import com.rainbowsea.yupicturebackend.exception.BusinessException;
import com.rainbowsea.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/***
 * 提供通用的对象存储操作，比如文件上传、文件下载等。
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;




    /**
     * 上传对象（附带图片信息） 图片格式压缩为webp，以及图片缩略图处理
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,file);

        // 对图片进行处理(获取基本信息也被视为一种图片的处理)
        PicOperations picOperations = new PicOperations();
        // 1.表示返回原图信息
        picOperations.setIsPicInfo(1);

        // 2. 图片处理规则类
        List<PicOperations.Rule> rules = new ArrayList<>();
        // 图片压缩(转成 webp) 格式——规则 0
        String webpKey = FileUtil.mainName(key) + ".webp";
        PicOperations.Rule compressRule = new PicOperations.Rule();
        compressRule.setBucket(cosClientConfig.getBucket());  // 设置哪个对象存储桶
        compressRule.setFileId(webpKey);
        compressRule.setRule("imageMogr2/format/webp");
        rules.add(compressRule);


        // 3. 缩略图处理，仅对 > 20 KB 的图片生成缩略图
        if (file.length() > 20 * 1024) {
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            // 缩放规则 /thumbnail/<Width>x<Height>>（如果大于原图宽高，则不处理）
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 128, 128));
            rules.add(thumbnailRule);
        }



        // 构造处理参数
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }




        /**
         * 下载对象
         *
         * @param key 唯一键
         */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }


    // ... 一些操作 COS 的方法
    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }


    /**
     * 删除对象
     *
     * @param key 文件 key
     */
    public void deleteObject(String key) throws CosClientException {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }


    /**
     * to do 以图搜图 webp 图片搜索问题方案1,
     * 将COS中的文件下载到本地
     * @param filepath  文件路径，如folder/picture.jpg
     * @param localPath 本地存储路径
     */
    //public void downloadPicture(String filepath, String localPath) throws IOException {
    //    File file = new File(localPath);
    //    COSObjectInputStream cosObjectInput = null;
    //    try {
    //        COSObject cosObject = this.getObject(filepath);
    //        cosObjectInput = cosObject.getObjectContent();
    //        // 将输入流转为字节数组
    //        byte[] data = IOUtils.toByteArray(cosObjectInput);
    //        // 将字节数组写入本地文件
    //        FileUtil.writeBytes(data, file);
    //    } catch (Exception e) {
    //        log.error("file download error, filepath = {}", filepath, e);
    //        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
    //    } finally {
    //        if (cosObjectInput != null) {
    //            cosObjectInput.close();
    //        }
    //    }
    //}


}
